const { readFileSync } = require('fs')

const { resolve } = require('path')

const {compileHTML} = require('./compiler')

const INNER_MARK = '<!--inner-->'

class MdToHtmlPlugin{
  constructor({template,filename}) {
    if (!template){
      throw new Error('the config for "Template must be configured" ')
    }
    this.template = template;
    this.filename = filename ? filename : 'md.html'
  }

  apply(compiler){
    compiler.hooks.emit.tap('md-to-html-plugin',(compilation)=>{
      const _assets = compilation.assets;
      console.log(_assets)
      //readFileSync 同步
      const _mdContent = readFileSync(this.template,'utf-8')
      const _templateHtml = readFileSync(resolve(__dirname,"template.html"),'utf-8')
      // 变为数组
      const _mdContentArr = _mdContent.split('\n');

      // 替换为标签
      const _htmlStr = compileHTML(_mdContentArr)

      console.log(_htmlStr)


      const _fileHtml = _templateHtml.replace(INNER_MARK,_htmlStr)


      _assets[this.filename]={
        source(){
          return _fileHtml
        },
        size(){
          return _fileHtml.length
        }
      }

      //
      // console.log(_mdContent)
      // console.log(_templateHtml)
      // console.log(_mdContentArr)
    })
  }
}

module.exports = MdToHtmlPlugin;